package mark.tom.friend;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

class DefaultFacade implements Facade {

    private ContentResolver contentResolver;
    private ContentChecker serverChecker, extraChecker;
    private CheckResultNotifier checkResult;

    DefaultFacade(@NonNull FRollBuilder builder) {
        this.contentResolver = builder.contentResolver;
        this.serverChecker = builder.serverChecker;
        this.extraChecker = builder.extraChecker;
        this.checkResult = builder.checkResult;
        // 初始化通知器
        this.checkResult = null == checkResult ? new CheckResultNotifier.LOG() : checkResult;
    }

    @Override
    @SuppressLint("LogNotTimber")
    public ConfigContent execute(@NonNull String packageName) {
        ConfigContent configContent = ConfigContentProvider.getContent(contentResolver, packageName);
        if (configContent.isDebugAble()) {
            if (checkContent(packageName, configContent.getServerConfig(), serverChecker, checkResult)) {
                Log.d("FRoll", "Check Success");
            } else {
                configContent.setServerConfig(null);
            }
            if (!checkContent(packageName, configContent.getExtraConfig(), extraChecker, checkResult)) {
                configContent.setExtraConfig(null);
            }
        }
        return configContent;
    }

    private boolean checkContent(String packageName, String content, ContentChecker contentChecker
            , CheckResultNotifier checkResultNotifier) {
        boolean result = true;
        if (!TextUtils.isEmpty(content) && null != contentChecker && !contentChecker.check(packageName, content)) {
            checkResultNotifier.notify("Config Check error : packageName is " + packageName + " content is " + content);
            result = false;
        }
        return result;
    }
}
